const express = require('express');
const router = express.Router();
const { User } = require('../../models');
const { Op } = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/**
 * 公共方法：查询当前用户
 */
async function getUser(req) {
   // 获取用户 ID
  const { id } = req.params;

   // 查询当前用户
  const user = await User.findByPk(id);

  // 如果没有找到，就抛出异常
  if (!user) {
    throw new NotFoundError(`ID: ${ id }的用户未找到。`)
  }

  return user;
}
/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    email: req.body.email,
    username: req.body.username,
    password: req.body.password,
    nickname: req.body.nickname,
    sex: req.body.sex,
    company: req.body.company,
    introduce: req.body.introduce,
    role: req.body.role,
    avatar: req.body.avatar
  };
}
/**
 * 查询用户列表
 * GET /admin/user
 */
router.get('/', async function (req, res) {
  try {
    // 定义查询条件
   
      const { username ,email, nickname,role, page , size} = req.query; 

      if (username) {
        condition.where.username = {
              [Op.like]: `%${username}%`
            }
      }
      if (email) {
           condition.where.email = {
              [Op.like]: `%${email}%`
            }
      }
      if (nickname) {
            condition.where.nickname = {
              [Op.like]: `%${nickname}%`
            }
      }
      if (role) {
           condition.where.role = role;
       }
      const pageNum = page ? page : 1;
      const condition = {
          order: [['id', 'DESC']],
          offset: Number((pageNum - 1) * size),
          limit: Number(size)
      };
    // 查询数据
    const  { count, rows } = await User.findAndCountAll(condition);

    // 返回查询结果
    success(res, '查询用户列表成功。', {
      data: rows,
      pagination: {
        total: count,
        page,
        size,
      }
    });
  } catch (error) {
    // 返回错误信息
    failure(res, error);
  }
});
/**
 * 查询用户详情
 */
router.get('/:id', async function (req, res) {
    try {
        const user = await getUser(req);
        success(res, '查询用户成功。', { user });
        
    } catch (error) {
        failure(res, error);
    }
})
 /**
  * 创建用户
  */
router.post("/", async function (req, res) {
    try {
        const body = filterBody(req);
        const user = await User.create(body);
        success(res, '创建用户成功。', { user }, 201);
    } catch (error) {
      failure(res, error);

    }
})
/**
 * 删除用户
 */
router.delete('/:id', async function (req, res) {
    try {
        const user = await getUser(req);
        await user.destroy()
        success(res, '删除用户成功。');
        
    } catch (error) {
        failure(res, error);
    }
})
/**
 * 更新用户
 */
router.put('/:id', async function (req, res) {
    try {
        const user = await getUser(req);
        const body = filterBody(req);
        await user.update(body)
        success(res, '更新用户成功。', { user });
        
    } catch (error) {
        failure(res, error);
    }
})
module.exports = router;
